package com.qf.fmall2204.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2204.user.entity.User;
import com.qf.fmall2204.user.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    IUserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String username = (String) token.getPrincipal();

        // 根据用户名查询数据库中的用户信息
        User dbuser = userService.getOne(new QueryWrapper<User>().eq("username", username));

        if (dbuser==null){
            throw new RuntimeException("用户名不存在，登录失败");
        }

        // 将密码、盐封装到shiro的AuthenticationInfo对象中
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(dbuser, dbuser.getPassword(),
                ByteSource.Util.bytes(dbuser.getSalt()), this.getName());


        return simpleAuthenticationInfo;
    }
}
